import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { RootPage, BlankPage } from '@/layouts'
import type { AppRouterRecordRaw } from './types'
import { getCache } from '@/utils/cache'
import { CACHE_KEY } from '@/enums/cacheEnum'

// 将静态路由
const routersList: AppRouterRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    meta: {
      title: '仪表盘'
    },
    redirect: '/dashboard',
    component: RootPage,
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        meta: {
          title: '工作台'
        },
        component: () => import('@/views/HomeView.vue')
      }
    ]
  },
  {
    path: '/',
    name: 'blank',
    component: BlankPage,
    meta: {
      title: '登录',
      hidden: true
    },
    children: [
      {
        path: 'login',
        name: 'login',
        meta: {
          title: '登录',
          hidden: true
        },
        component: () => import('@/views/LoginView.vue')
      }
    ]
  }
]

const routes = import.meta.glob('./modules/*.ts', { eager: true })
Object.keys(routes).forEach((key) => {
  const route = routes[key].default
  routersList.push(route)
})

export function getRoutes() {
  return routersList
}

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routersList as unknown as RouteRecordRaw[]
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title as string + ' - 广西城市职业大学机械协会'
  if (!getCache(CACHE_KEY.TOKEN) && to.name !== 'login') {
    next({ name: 'login' })
    return
  }
  next()
})

export default router
